package com.wyp168.leetcode;

/**
 * @ClassName Decrypt
 * @Description TODO
 * @Author wyp168
 * @Date 2022/9/24 00:18
 */
public class DecryptSolution {
    public static void main(String[] args) {
        int[] code = {2,4,9,3};
        int k = -2;
        DecryptSolution decryptSolution = new DecryptSolution();
        int[] res = decryptSolution.decrypt(code, k);
        for (int item : res) {
            System.out.println(item);
        }
    }
    /**
     * 如果k > 0，将第i个数字用 接下来k个数字之和替换。
     * 如果k < 0，将第i个数字用 之前k个数字之和替换。
     * 如果k == 0，将第i个数字用0替换。
     *
     * @param code
     * @param k
     * @return
     */
    public int[] decrypt(int[] code, int k) {
        int size = code.length;
        int[] res = new int[size];
        if (k == 0) {
            return res;
        } else if (k < 0) {
            for (int i = 0; i < size; i++) {
                int j = i - 1;
                if (j < 0) {
                    j = size - 1;
                }
                int loopCount = -k;
                int tempSum = 0;
                while (0 < loopCount) {
                    tempSum += code[j];
                    j --;
                    loopCount --;
                    if (j < 0) {
                        j = size - 1;
                    }
                }
                res[i] = tempSum;
            }
        } else {
            for (int i = 0; i < size; i++) {
                int j = i + 1;
                if (j == size) {
                    j = 0;
                }
                int loopCount = k;
                int tempSum = 0;
                while (0 < loopCount) {
                    tempSum += code[j];
                    j ++;
                    loopCount --;
                    if (j == size) {
                        j = 0;
                    }
                }
                res[i] = tempSum;
            }
        }
        return res;
    }
}
